package com.qf.controller;

import com.event.util.EventUtil;
import com.qf.annotation.IsLogin;
import com.qf.aop.UserLocal;
import com.qf.entity.Coupon;
import com.qf.entity.R;
import com.qf.feign.CouponFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/kill")
public class KillController {

    @Autowired
    private CouponFeign couponFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private EventUtil eventUtil;

    private String lua = "--抢劵的lua脚本\n" +
            "local key = \"coupon_save\"\n" +
            "--优惠券id\n" +
            "local cid = KEYS[1]\n" +
            "--用户id\n" +
            "local uid = ARGV[1]\n" +
            "local field = \"save_\"..cid\n" +
            "local value = uid..'-'..cid\n" +
            "\n" +
            "--判断是否领取过\n" +
            "local result = redis.call('sismember', 'couponget', value)\n" +
            "if result == 1 then\n" +
            "     --说明已经抢过该优惠券\n" +
            "     return -1\n" +
            "end\n" +
            "\n" +
            "\n" +
            "--判断库存\n" +
            "local save = tonumber(redis.call('hget', key, field) or -1)\n" +
            "if save < 1 then\n" +
            "    --库存不足\n" +
            "    return 0\n" +
            "end\n" +
            "\n" +
            "--库存充足，修改库存\n" +
            "save = save - 1\n" +
            "redis.call('hset', key, field, save)\n" +
            "\n" +
            "--将用户id和优惠券id记录到redis中\n" +
            "redis.call('sadd', 'couponget', value)\n" +
            "\n" +
            "return 1";


    /**
     * 获得当前时间
     * @return
     */
    @RequestMapping("/now")
    public R getNow(){
        return new R().setData(new Date().getTime());
    }
    
    /**
     * 获得当前显示抢劵的时间段
     * @return
     */
    @RequestMapping("/getTimes")
    public R getKillTimes(){

        //获得当前的3个时间段 8 10 12 14 16 ...
        //获得当前时间
        Calendar calendar = Calendar.getInstance();


        List<Map<String, Object>> times = new ArrayList<>();

        //循环3次
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        for (int i = 0; i < 3; i++) {
            calendar.set(Calendar.HOUR_OF_DAY, hour % 2 == 0 ? hour : hour - 1);
            calendar.add(Calendar.HOUR_OF_DAY, 2 * i);//0 2 4
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Map<String, Object> map = new HashMap();
            map.put("showTime", calendar.get(Calendar.HOUR_OF_DAY) + "点场");
            map.put("nowTime", calendar.getTime().getTime());
            times.add(map);
        }

        return new R().setData(times);
    }

    /**
     * 根据时间段，获取优惠券列表
     * @param index
     * @return
     */
    @RequestMapping("/getCouponByTime")
    public R getCouponByTime(Integer index){

        //获取需要查询的时间
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        hour = (hour % 2 == 0 ? hour : hour - 1) + index * 2;
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        //通过Feign调用优惠券服务，查询优惠券
        List<Coupon> coupons = couponFeign.queryByTimes(calendar.getTime()).getData();
        System.out.println("查询到" + hour + "点场次的优惠券列表：" + coupons);
        return new R().setData(coupons);
    }

    /**
     * 抢劵的接口
     * @param cid - 优惠券id
     * @return
     */
    @IsLogin(mustLogin = true)
    @RequestMapping("/qiangjuan")
    public R qiangJuan(Integer cid){
        System.out.println(UserLocal.getUser().getId() + "用户抢劵：" + cid);

        Long result = redisTemplate.execute(
                new DefaultRedisScript<>(lua, Long.class),
                Collections.singletonList(cid + ""),
                UserLocal.getUser().getId() + "");

        if (result == 1) {
            //通过MQ的形式通知优惠券服务修改优惠券库存以及生成领取记录
            Map map = new HashMap();
            map.put("uid", UserLocal.getUser().getId());
            map.put("cid", cid);
            eventUtil.publishEvent("coupon_get", map);

            //抢劵成功
            return new R().setData(true);
        } else if (result == 0) {
            return new R().setCode(R.Code.ERROR).setMsg("优惠券已经抢完！");
        } else {
            return new R().setCode(R.Code.ERROR).setMsg("优惠券已经领取，请勿重复领取！");
        }
    }
}
